package com.black.common.mybatis;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.black.common.mybatis.service.DataScopeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Connection;

/**
 * @author linwenfeng
 */
@Slf4j
public class DataScopeInterceptor implements InnerInterceptor {

    @Autowired
    DataScopeService dataScopeService;

    @Override
    public void beforePrepare(StatementHandler statementHandler, Connection connection, Integer transactionTimeout) {
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        // 先判断是不是SELECT操作 不是直接过滤
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return;
        }
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        // 执行的SQL语句
        String powerSql = boundSql.getSql();
        try {
            powerSql = dataScopeService.handler(boundSql.getSql(), mappedStatement.getId());
        } catch (Exception exception) {
            log.error("数据权限处理异常",exception);
        }
        metaObject.setValue("delegate.boundSql.sql", powerSql);
    }
}
